package com.jky.filesystem;

import com.jky.filesystem.Data.CommonData;
import com.jky.filesystem.utils.PermissionsUtils;
import ohos.aafwk.content.IntentParams;
import ohos.ace.ability.AceAbility;
import ohos.aafwk.content.Intent;
import ohos.event.commonevent.*;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.rpc.RemoteException;

public class MainAbility extends AceAbility {
    private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD001100, "测试MainAbilityLOG");
    private MyCommonEventSubscriber subscriber;
    @Override
    public void onStart(Intent intent) {
        HiLog.error(LABEL_LOG,"onStart");
        changePage(intent,true);
        subscribe();
        super.onStart(intent);
        PermissionsUtils.requestRemotePermission(this);
    }

    @Override
    public void onStop() {
        unSubscribe();
        super.onStop();
    }

    //订阅事件
    public void subscribe() {
        MatchingSkills matchingSkills = new MatchingSkills();
        matchingSkills.addEvent(CommonData.ROUTE_EVENT);
        CommonEventSubscribeInfo subscribeInfo = new CommonEventSubscribeInfo(matchingSkills);
        subscriber = new MyCommonEventSubscriber(subscribeInfo);
        try {
            CommonEventManager.subscribeCommonEvent(subscriber);
            HiLog.info(LABEL_LOG,"订阅事件");
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
    //取消订阅
    private void unSubscribe() {
        try {
            CommonEventManager.unsubscribeCommonEvent(subscriber);
        } catch (RemoteException e) {
            HiLog.error(LABEL_LOG, "unSubscribe Exception");
        }
    }

    //跳转函数，处理mainability是否已经被打开，被打开则跳转，没被打开则设置初始页
    public void changePage(Intent intent,Boolean isFirst) {
        String route = intent.getStringParam(CommonData.KEY_JS_ROUTE);
        if(route != null && !route.isEmpty()) {
            HiLog.info(LABEL_LOG,"跳转到：" + route);
            IntentParams intentParams = new IntentParams();
            intentParams.setParam(CommonData.JS_ROUTE_PARAMS_KEY,true);
            if(isFirst) {
                setPageParams(route,intentParams);
            }
            else {
                pushPage(route, intentParams);
            }
        }
    }

    //事件接收
    class MyCommonEventSubscriber extends CommonEventSubscriber {

        public MyCommonEventSubscriber(CommonEventSubscribeInfo subscribeInfo) {
            super(subscribeInfo);
        }

        @Override
        public void onReceiveEvent(CommonEventData commonEventData) {
            HiLog.info(LABEL_LOG,"接收到事件被调用");
            Intent intent = commonEventData.getIntent();
            String route = intent.getStringParam(CommonData.KEY_JS_ROUTE);
            changePage(intent,false);
        }
    }

}
